package org.springblade.mach.ziputils;

import jodd.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springblade.modules.resource.entity.Attach;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

import java.net.URL;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author LY
 * @version 1.0
 * @date 2021/5/13 15:32
 *
 * 批量下载时 操作的工具类
 */
@Component
@Slf4j
public class ZipUtil {
	private static final int BUFFER_SIZE = 2 * 1024;
	public void toZip(List<Attach> srcFiles, OutputStream out) throws RuntimeException {
		long start = System.currentTimeMillis();
		ZipOutputStream zos = null;
		try {
			zos = new ZipOutputStream(out);
			for (Attach srcFile : srcFiles) {
				byte[] buf = new byte[BUFFER_SIZE];
				zos.putNextEntry(new ZipEntry(srcFile.getOriginalName()));
				// 网路地址
				URL url = new URL(srcFile.getLink());
				int len;
				// 网络中流
				InputStream in = url.openConnection().getInputStream();
				while ((len = in.read(buf)) != -1) {
					zos.write(buf, 0, len);
				}
				zos.closeEntry();
				in.close();
			}
			long end = System.currentTimeMillis();
			System.out.println("压缩完成，耗时：" + (end - start) + " ms");
		} catch (Exception e) {
			throw new RuntimeException("zip error from ZipUtils", e);
		} finally {
			if (zos != null) {
				try {
					zos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}


	private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception {

		byte[] buf = new byte[BUFFER_SIZE];
		if (sourceFile.isFile()) {
			// 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
			zos.putNextEntry(new ZipEntry(name));
			// copy文件到zip输出流中
			int len;
			FileInputStream in = new FileInputStream(sourceFile);

			while ((len = in.read(buf)) != -1) {
				zos.write(buf, 0, len);
			}
			// Complete the entry
			zos.closeEntry();
			in.close();
		} else {
			File[] listFiles = sourceFile.listFiles();
			if (listFiles == null || listFiles.length == 0) {
				// 需要保留原来的文件结构时,需要对空文件夹进行处理
				if (KeepDirStructure) {
					// 空文件夹的处理
					zos.putNextEntry(new ZipEntry(name + "/"));
					// 没有文件，不需要文件的copy
					zos.closeEntry();
				}
			} else {
				for (File file : listFiles) {
					// 判断是否需要保留原来的文件结构
					if (KeepDirStructure) {
						// 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
						// 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
						compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
					} else {
						compress(file, zos, file.getName(), KeepDirStructure);
					}
				}
			}
		}
	}

//	public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException {
//
//		long start = System.currentTimeMillis();
//		ZipOutputStream zos = null;
//		try {
//			zos = new ZipOutputStream(out);
//
//			File sourceFile = new File(srcDir);
//			compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
//			long end = System.currentTimeMillis();
//			log.info("压缩完成，耗时：" + (end - start) + " ms");
//		} catch (Exception e) {
//			throw new RuntimeException("zip error from ZipUtils", e);
//		} finally {
//			if (zos != null) {
//				try {
//					zos.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}
//	}
	public static void toZip(List<Attach> srcFiles, OutputStream out, boolean KeepDirStructure) throws RuntimeException {

		long start = System.currentTimeMillis();
		ZipOutputStream zos = null;
		for (Attach srcFile : srcFiles) {
			try {
				zos = new ZipOutputStream(out);
				URL url = new URL(srcFile.getLink());
				File sourceFile = new File(url.toURI());

				compress(sourceFile, zos,  sourceFile.getName(), KeepDirStructure);

				long end = System.currentTimeMillis();
				log.info("压缩完成，耗时：" + (end - start) + " ms");
			} catch (Exception e) {
				throw new RuntimeException("zip error from ZipUtils", e);
			}
		}
		if (zos != null) {
			try {
				zos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public static File getFile(String url) throws Exception {
		//对本地文件命名
		String fileName = url.substring(url.lastIndexOf("."),url.length());

		File file = null;

		URL urlfile;
		InputStream inStream = null;

		OutputStream os = null;
		try {
			file = File.createTempFile("net_url", fileName);
			//下载
			urlfile = new URL(url);
			inStream = urlfile.openStream();
			os = new FileOutputStream(file);

			int bytesRead = 0;
			byte[] buffer = new byte[BUFFER_SIZE];
			while ((bytesRead = inStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != os) {
					os.close();
				}
				if (null != inStream) {
					inStream.close();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return file;
	}






//		MinioClient client = MinioOssBuilder.getMinooClient(ossBuilder.getOss(AuthUtil.getTenantId(), StringPool.EMPTY));
//		Attach attach = attachByInfoId.get(0);
//		InputStream in = null;
//		try {
//			//获取文件对象 stat原信息
//			ObjectStat stat = minioClient.statObject("000000-machtech", attach.getName());
//			response.setContentType(stat.contentType());
//			response.setCharacterEncoding("UTF-8");
//			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(attach.getName(), "UTF-8"));
//			in =   minioClient.getObject("000000-machtech", attach.getName());
//			System.out.println("reponse---->"+response.getOutputStream());
//			IOUtils.copy(in, response.getOutputStream());
//		}catch (Exception e){
//			e.printStackTrace();
//		}finally {
//			if(in!=null){
//				try {
//					in.close();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//		}

}
